import React, { Component, Suspense } from "react";
import { connect } from "dva";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { List, Button, Card, Form, Input, message, Select, Spin, Tag, Icon, Modal, Tooltip, Switch } from "antd";
import moment from "moment";
import styles from "./index.less";
import { getAgentList, getAgentDel, postAgentDisabled } from "@/services/assistantCenter";
import AddAgent from "./add";
import u172 from '@/assets/modelInstruction/u172.svg';

class AgentList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            total: 0,
            queryData: {
                search: "",
                current: 1,
                size: 16,
            }
        }
    };

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this);
        };
    }

    getList = async (categoryId, current) => {
        const { queryData } = this.state;
        let obj = { ...queryData, current: current ? current : queryData.current };
        switch (categoryId) {
            case "All":
                obj.categoryId = undefined;
                obj.type = undefined;
                break;

            case "Admin":
                obj.categoryId = undefined;
                obj.type = '1';
                break;

            default:
                obj.categoryId = categoryId;
                obj.type = '0';
                break;
        };
        let res = await getAgentList(obj);
        console.log(res);
        this.setState({ list: res.records, total: res.total });
    }

    queryByPage = () => {
        const { categoryKey } = this.props;
        let { queryData } = this.state;
        let userInfo = this.props.form.getFieldsValue();
        console.log(userInfo);
        queryData.current = 1;
        queryData.search = userInfo.search;
        this.setState({ queryData }, () => this.getList(categoryKey, 1))
    }

    fenye = (page) => {
        const { categoryKey } = this.props;
        let { queryData } = this.state;
        queryData.current = page;
        this.setState({ queryData }, () => this.getList(categoryKey, null));
    };

    addAgent = () => {
        if (this.addAgentRef) {
            this.addAgentRef._init_();
        }
    }

    editAgent = row => {
        if (this.addAgentRef) {
            this.addAgentRef._init_(row);
        }
    }

    delAgent = id => {
        const { categoryKey } = this.props;
        Modal.confirm({
            content: '确定删除当前agent吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            maskStyle: { zIndex: 99999 },
            zIndex: 999999,
            onOk: async () => {
                let res = await getAgentDel({ id });
                console.log(res);
                if (res.code === 0) {
                    message.success('操作成功');
                    this.getList(categoryKey, null);
                }
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    onSwitchChange = async (checked, id) => {
        const { categoryKey } = this.props;
        let res = await postAgentDisabled({ id, disabled: !checked });
        console.log(res);
        if (res.code === 0) {
            this.getList(categoryKey, null)
        }
    }

    render() {
        const { list, total, queryData } = this.state;
        const { categoryList, categoryId, categoryKey } = this.props;
        const { getFieldDecorator } = this.props.form;

        return (
            <div className={styles.cardBody}>
                <div className={styles['instruct-flex']} style={{ marginBottom: 20 }}>
                    <Form layout="inline">
                        <Form.Item>
                            {getFieldDecorator("search")(<Input placeholder="搜索助手名称" style={{ width: '240px' }} />)}
                        </Form.Item>
                        {/* <Form.Item>
                            {getFieldDecorator("type", { initialValue: null })(
                                <Select allowClear style={{ width: '240px' }}>
                                    <Select.Option value={null}>全部</Select.Option>
                                    <Select.Option value={0}>自建</Select.Option>
                                    <Select.Option value={1}>供应商授权</Select.Option>
                                </Select>
                            )}
                        </Form.Item> */}
                        <Form.Item>
                            <Button type="primary" onClick={this.queryByPage}>查询</Button>
                        </Form.Item>
                    </Form>
                    <Button type="primary" onClick={this.addAgent}>创建助手</Button>
                </div>
                <List
                    rowKey='id'
                    pagination={{
                        onChange: (page) => this.fenye(page),
                        current: queryData.current,
                        pageSize: 16,
                        total: parseInt(total),
                        showQuickJumper: true,
                    }}
                    grid={{ gutter: 16, column: 4 }}
                    dataSource={list}
                    renderItem={(item) => (
                        <List.Item key={item.id}>
                            <Card hoverable className={styles.cardOutBox} bodyStyle={{ padding: 0 }}>
                                <div className={styles.cardBox} style={{ padding: '18px 18px 0' }}>
                                    <img src={fileUrl + item.avatar} className={styles.titleImg} />
                                    <div style={{ flex: 1 }}>
                                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                                            <div className={styles.title}>{item.name}</div>
                                            <div>
                                                {item.sysShare ? null : (
                                                    <Switch checked={!item.disabled} onChange={checked => this.onSwitchChange(checked, item.id)} />
                                                )}
                                            </div>
                                        </div>
                                        <Tooltip placement="bottom" title={<div dangerouslySetInnerHTML={{ __html: item.introduction }}></div>}>
                                            <div className={`${styles['card-item-list']}`}>
                                                <p
                                                    dangerouslySetInnerHTML={{ __html: item.introduction }}
                                                    style={{ WebkitBoxOrient: 'vertical', minHeight: '50px', }}
                                                />
                                            </div>
                                        </Tooltip>
                                    </div>
                                </div>
                                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: '18px 18px 0' }}>
                                    <span style={{ display: "flex", alignItems: "center", gap: '12px' }}>
                                        <span
                                            style={{
                                                padding: '3px 8px',
                                                background: '#46d036',
                                                color: '#FFF',
                                                borderRadius: '5px',
                                                fontSize: '13px',
                                                whiteSpace: 'nowrap',
                                            }}
                                        >
                                            {item.sysShare ? "供应商授权" : "自建"}
                                        </span>
                                        <span style={{ display: "flex", alignItems: "center", gap: '8px' }}>
                                            <Icon type="fire" theme="twoTone" twoToneColor="#F5310D" />
                                            <span>{item.clicks}</span>
                                        </span>
                                    </span>
                                    <span
                                        style={{
                                            display: "flex",
                                            alignItems: "center",
                                            gap: '16px',
                                            color: '#AAAAAA',
                                            whiteSpace: 'nowrap',
                                        }}
                                    >
                                        {item.sysShare ? "@管理员" : ""}
                                    </span>
                                </div>
                                <div
                                    style={{
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: 'space-around',
                                        background: '#666',
                                        color: '#FFF',
                                        padding: '12px 0',
                                        marginTop: 18,
                                        borderRadius: '0 0 8px 8px',
                                    }}
                                >
                                    {item.sysShare ? (
                                        <>
                                            <div style={{ width: '30%', textAlign: 'center', userSelect: 'none' }} onClick={() => this.editAgent(item.id)}>查看</div>
                                        </>
                                    ) : (
                                        <>
                                            <div style={{ width: '30%', textAlign: 'center', userSelect: 'none' }} onClick={() => this.delAgent(item.id)}>删除</div>
                                            {/* <div style={{ width: '30%', textAlign: 'center', userSelect: 'none' }}>授权</div> */}
                                            <div style={{ width: '30%', textAlign: 'center', userSelect: 'none' }} onClick={() => this.editAgent(item.id)}>编辑</div>
                                        </>
                                    )}
                                </div>
                            </Card>
                        </List.Item>
                    )}
                />
                <AddAgent
                    onRef={ref => this.addAgentRef = ref}
                    getList={this.getList}
                    categoryList={categoryList}
                    categoryKey={categoryKey}
                />
            </div>
        );
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(Form.create()(AgentList));
